Webdevelopment: Calculate maximum image for given container size

Last update: 3/16/2020, 8:11:02 PM

An algorithm for fitting an image into a container, keeping original aspect ratio, maximizing image size in the available box.

const sourceRatio = originalImageWidth / originalImageHeight
const targetRatio = containerWidth / containerHeight

if (sourceRatio > targetRatio) {
  imageWidth = containerWidth
  imageHeight = Math.round(containerWidth * sourceRatio)
} else {
  imageWidth = Math.round(containerHeight * sourceRatio)
  imageHeight = containerHeight
}

Credits to Andrew Shepherd https://stackoverflow.com/a/15398653/26496